$("#close").on("click", () => {
  window.ipcRenderer.send("closeAddServe");
});
const setServe = () => {
  if ($("#official-servers").prop("checked")) {
    $(".server-about").text(
      "您现在正在使用官方服务器,官方服务器可能会出现卡顿、维护的情况，请您谅解，我们会尽最大努力保持服务的稳定性和可靠性。"
    );
    $(".server-input").hide();
  } else {
    $(".server-about").text("");
    $(".server-input").show();
    $("#input-name")[0].focus();
  }
};
setServe();
$("#official-servers").on("change", setServe);
$("#custom-servers").on("change", setServe);

const channel = new BroadcastChannel("updataServerList");

$(".serve-finish").on("click", EnterFinish);
async function EnterFinish() {
  const form = [];
  let state = false;
  $(".server-input input").each((index, ele) => {
    if (ele.value === "" && index <= 1) state = true;
    form[index] = ele.value;
  });
  $(".isEmpty-jq").hide();
  if (state && !$("#official-servers").prop("checked")) {
    await new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, 100);
    });
    $(".isEmpty-jq").show();
    return;
  }
  const serverUrl = $("#official-servers").prop("checked")
    ? `${ipConfig.url}`
    : form[1];
  $(".load").show();
  $.post(`${serverUrl}/api/connect`, {password: form[2]})
    .then(async (res) => {
      $(".load").hide();
      if (res.status) {
        window.ipcRenderer.send("connctError", [
          "error",
          "连接失败",
          "服务器密码错误!",
          ["ok"],
        ]);
        return;
      }
      window.ipcRenderer.send("savaServer", {
        name: $("#official-servers").prop("checked")
          ? "WeTalk官方服务器"
          : form[0],
        ip: $("#official-servers").prop("checked") ? ipConfig.url : form[1],
        password: form[2],
      });
      channel.postMessage("check up!");
      window.ipcRenderer.send("closeAddServe");
    })
    .catch(() => {
      $(".load").hide();
      $(".timeout-container").show();
    });
}
$(window).on("click", () => {
  $(".timeout-container").hide();
});
$(window).on("keydown", (e) => {
  if (e.key === "Enter") EnterFinish();
});
